/**
 * Auto gen via dbpojo-gen.
 */
package com.us.usws.service.cud.impl;

import java.util.Date;

import net.iwsh.core.common.GlobalConfig;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.us.usws.common.SiteConstants;
import com.us.usws.dao.MobileAuthDAO;
import com.us.usws.model.domain.system.MobileAuth;
import com.us.usws.model.flat.system.DOMobileAuth;
import com.us.usws.service.cud.MobileAuthCUDService;

/**
 * Service RO impl class
 * @author robot
 */
public class MobileAuthCUDServiceImpl implements MobileAuthCUDService {

	/**
	 * DAO instance
	 */
	private MobileAuthDAO dao = new MobileAuthDAO();

	/**
	 * Insert one row.
	 */
	@Override
	public int addMobileAuth(DOMobileAuth mobileAuth) {
		return (int) dao.insertMobileAuth(mobileAuth);
	}

	/**
	 * Update by PK.
	 */
	@Override
	public void updateMobileAuth(DOMobileAuth mobileAuth) {
		dao.updateMobileAuth(mobileAuth);
	}

	/**
	 * Delete row by PK.
	 */
	@Override
	public void deleteMobileAuth(Integer id) {
		dao.deleteMobileAuth(id);
	}

	@Override
	public MobileAuth generateNewForgotPasswordAuth(String mobileNo, String epToken, String userUid) {
		MobileAuth ma = genDefaultMobileAuth(mobileNo, epToken, userUid);
		ma.setAuthTypeDsid(SiteConstants.DSID_MOBILE_AUTH_TYPE_FORGOT_PASSWORD);
		long id = dao.insertMobileAuth(ma);
		ma.setId((int) id);
		return ma;
	}

	@Override
	public MobileAuth generateNewActivateUserAuth(String mobileNo, String epToken, String userUid) {
		MobileAuth ma = genDefaultMobileAuth(mobileNo, epToken, userUid);
		ma.setAuthTypeDsid(SiteConstants.DSID_MOBILE_AUTH_TYPE_ACTIVATE_USER);
		long id = dao.insertMobileAuth(ma);
		ma.setId((int) id);
		return ma;
	}

	/**
	 * private call
	 */
	private MobileAuth genDefaultMobileAuth(String mobileNo, String epToken, String userUid) {
		MobileAuth ma = new MobileAuth();
		int len = GlobalConfig.getInt("EpUser/AuthCodeLen", 6);
		int expiresMin = GlobalConfig.getInt("EpUser/AuthCodeExpiresMinute", 10);

		String authCode = RandomStringUtils.randomNumeric(len);
		ma.setAuthCode(authCode);

		Date now = new Date();
		ma.setCreateDate(now);
		ma.setEndDate(DateUtils.addMinutes(now, expiresMin));
		ma.setEpToken(epToken);

		ma.setMobileNo(mobileNo);
		ma.setUserUid(userUid);
		return ma;
	}

}